package com.hitfm.iplay.activity;

import java.io.File;
import java.io.FilenameFilter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.hitfm.iplay.MusicInfoController;
import com.hitfm.iplay.MusicPlayerApp;
import com.hitfm.iplay.MusicPlayerService;
import com.hitfm.iplay.R;
import com.hitfm.iplay.db.RecentplayDAO;
import com.hitfm.iplay.util.ConvertTime;
import com.hitfm.iplay.util.SDCardOperation;

public class MysongActivity extends Activity {
	public static final String KEY_ID = "_id";
	public static final String KEY_URL = "url";
	public static final String KEY_SINGER = "singer";
	public static final String KEY_SONGNAME = "songname";
	public static final String KEY_ALBUM = "album";
	private static MusicPlayerService mMusicPlayerService = null;
	private static MusicInfoController mMusicInfoController = null;
	private static Cursor mLocalCursor = null;
	private static final int ALLSONG = 0;
	private static final int FOLDER = 1;
	private static final int SINGER = 2;
	private static final int MYSONG_LAYOUT = 0;
	private static final int LOCALSONG_LAYOUT = 1;
	private static final int RECENT_LAYOUT = 2;
	private static final int LIST_LAYOUT = 3;
	private static final int FAVORITE_LAYOUT = 4;
	private static final int MOVEDSC = 20;
	private static int local_selected_button = 0;
	private static boolean local_ismoved = false;
	private static float local_movedX = 0;
	private static float local_movedY = 0;

	private static final String TAG = "iplay";
	protected static final int LOADING_DIALOG = 0;

	private static TextView mysong_localsong;
	private static TextView mysong_recentplay;
	private static TextView mysong_playlist;
	private static TextView mysong_favorite;
	protected static Intent intent;
	private static ImageView recent_backto_localsong;
	private static TextView local_allsong;
	private static TextView local_folder;
	private static TextView local_singer;
	private static ListView local_list_all;
	private static ListView local_list_folder;
	private static ListView recent_list;
	private static MusicListAdapter mLocalMusicListAdapter;
	private static MusicListAdapter mRecentMusicListAdapter;
	private static LinearLayout layout_mySong;
	private static RelativeLayout layout_localSongAll;
	private static LinearLayout layout_recentplay;
	private static Thread folderThread;

	private ServiceConnection mPlaybackConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			// mMusicPlayerService = ((MusicPlayerService.LocalBinder) service)
			// .getService();
			if (null != mMusicPlayerService && mMusicPlayerService.isPlaying()) {
				local_all_playing_id.setText(mMusicPlayerService.getInfo());
			}
		}

		public void onServiceDisconnected(ComponentName className) {
			mMusicPlayerService = null;
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mysong);
		findMySongViews();
		setMySongListeners();
		setBroadcast();
		mMusicPlayerService = MusicPlayerApp.getmMusicPlayerService();
	}

	private void setBroadcast() {
		IntentFilter playerFilter = new IntentFilter();
		playerFilter.addAction(MusicPlayerService.PLAYER_PREPARE_END);
		registerReceiver(mPlayerEvtReceiver, playerFilter);

	}

	protected BroadcastReceiver mPlayerEvtReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (null == mMusicPlayerService) {
				return;
			}
			String action = intent.getAction();
			if (action.equals(MusicPlayerService.PLAYER_PREPARE_END)) {
				// will begin to play
				local_all_playing_id.setText(mMusicPlayerService.isRandom() == true ? R.string.random_play : R.string.playing);
				local_all_playing_id.append("  " + mMusicPlayerService.getInfo());
			} else {
				local_all_playing_id.setText(R.string.stopplaying);
			}
		}
	};
	private static TextView local_all_playing_id;
	private static MusicPlayerApp musicPlayerApp;
	protected int layoutIndex = MYSONG_LAYOUT;
	private ProgressDialog dialog;
	private static ImageView local_folder_pre;
	private static Button local_folder_sdcard;
	private static LinearLayout layout_local_folderlist;
	private static LinearLayout layout_local_alllist;
	protected static FolderAdapter mFolderAdapter;
	private static File sdCardPath = new File(Environment.getExternalStorageDirectory().toString());;
	private static String folderPath = sdCardPath.getAbsolutePath();
	private static FilenameFilter mp3Filter;
	private static File[] folderListFiles;
	private static RelativeLayout layout_local_folder;
	private static RelativeLayout layout_local_all_playing_id;
	private static RecentplayDAO recentplayDAO;
	private static Cursor mRecentCursor;
	private static TextView recent_clear;
	private static ImageView local_backto_localsong;
	private static Handler handler;

	private void findMySongViews() {
		// 我的歌曲
		layout_mySong = (LinearLayout) findViewById(R.id.layout_mysong);
		mysong_localsong = (TextView) findViewById(R.id.local_song);
		mysong_recentplay = (TextView) findViewById(R.id.recent_play);
		mysong_playlist = (TextView) findViewById(R.id.playlist);
		mysong_favorite = (TextView) findViewById(R.id.favorite);
		// 本地歌曲
		layout_local_all_playing_id = (RelativeLayout) findViewById(R.id.layout_localsong_all_playing_id);
		layout_local_folder = (RelativeLayout) findViewById(R.id.layout_localsong_folder);
		layout_localSongAll = (RelativeLayout) findViewById(R.id.layout_localsong_all);
		layout_local_alllist = (LinearLayout) findViewById(R.id.layout_localsong_alllist);
		layout_local_folderlist = (LinearLayout) findViewById(R.id.layout_localsong_folderlist);
		local_backto_localsong = (ImageView) findViewById(R.id.local_backto_mysong);
		local_allsong = (TextView) findViewById(R.id.allsong);
		local_folder = (TextView) findViewById(R.id.folder);
		local_singer = (TextView) findViewById(R.id.singer);
		local_all_playing_id = (TextView) findViewById(R.id.playing_id);
		local_list_all = (ListView) findViewById(R.id.list_localsong_all);
		local_list_folder = (ListView) findViewById(R.id.list_localsong_folder);
		local_folder_sdcard = (Button) findViewById(R.id.localsong_folder_sdcard);
		local_folder_pre = (ImageView) findViewById(R.id.localsong_folder_pre);
		// 最近播放
		layout_recentplay = (LinearLayout) findViewById(R.id.layout_recentplay);
		recent_backto_localsong = (ImageView) findViewById(R.id.recent_backto_mysong);
		recent_clear = (TextView) findViewById(R.id.recentplay_clear);
		recent_list = (ListView) findViewById(R.id.list_recent);
	}

	private void setMySongListeners() {
		// 我的歌曲
		mysong_localsong.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				initService();
				layoutIndex = LOCALSONG_LAYOUT;
				layout_mySong.setVisibility(View.INVISIBLE);
				layout_localSongAll.setVisibility(View.VISIBLE);
				layout_recentplay.setVisibility(View.INVISIBLE);
				if (mLocalMusicListAdapter == null) {
					showDialog(LOADING_DIALOG);
					folderThread.start();
				}
			}
		});
		mysong_recentplay.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				showRecentList();
				layoutIndex = RECENT_LAYOUT;
				layout_mySong.setVisibility(View.INVISIBLE);
				layout_localSongAll.setVisibility(View.INVISIBLE);
				layout_recentplay.setVisibility(View.VISIBLE);
			}
		});
		// 本地歌曲
		local_backto_localsong.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				backToMysong();
			}
		});
		local_allsong.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (local_selected_button == ALLSONG) {
					return false;
				}
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					local_movedX = event.getX();
					local_movedY = event.getY();
					local_allsong.setBackgroundResource(R.drawable.all_selected);
					break;
				case MotionEvent.ACTION_UP:
					if (MysongActivity.local_ismoved) {
						local_allsong.setBackgroundResource(R.drawable.all_unselected);
					} else {
						layout_local_all_playing_id.setVisibility(View.VISIBLE);
						layout_local_alllist.setVisibility(View.VISIBLE);
						layout_local_folderlist.setVisibility(View.INVISIBLE);
						layout_local_folder.setVisibility(View.INVISIBLE);
						local_folder.setBackgroundResource(R.drawable.folder_unselected);
						local_singer.setBackgroundResource(R.drawable.singer_unselected);
						local_selected_button = ALLSONG;
					}
					MysongActivity.local_ismoved = false;
					break;
				case MotionEvent.ACTION_MOVE:
					if (Math.abs((event.getX() - local_movedX)) > MOVEDSC || Math.abs((event.getY() - local_movedY)) > MOVEDSC) {
						MysongActivity.local_ismoved = true;
					}
					break;
				default:
					break;
				}
				return true;
			}
		});
		local_folder.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (local_selected_button == FOLDER) {
					return false;
				}
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					local_movedX = event.getX();
					local_movedY = event.getY();
					local_folder.setBackgroundResource(R.drawable.folder_selected);
					break;
				case MotionEvent.ACTION_UP:
					if (MysongActivity.local_ismoved) {
						local_folder.setBackgroundResource(R.drawable.folder_unselected);
					} else {
						if (mFolderAdapter == null) {
							showDialog(LOADING_DIALOG);
							folderThread = new Thread() {
								public void run() {
									Looper.prepare();
									if (local_list_folder != null) {
										showFolder(sdCardPath.toString());
										handler.sendEmptyMessage(FOLDER);
									}
									Looper.loop();
								}
							};
							folderThread.start();
						}
						layout_local_all_playing_id.setVisibility(View.INVISIBLE);
						layout_local_folder.setVisibility(View.VISIBLE);
						layout_local_alllist.setVisibility(View.INVISIBLE);
						layout_local_folderlist.setVisibility(View.VISIBLE);
						local_allsong.setBackgroundResource(R.drawable.all_unselected);
						local_singer.setBackgroundResource(R.drawable.singer_unselected);
						local_selected_button = FOLDER;
					}
					MysongActivity.local_ismoved = false;
					break;
				case MotionEvent.ACTION_MOVE:
					if (Math.abs((event.getX() - local_movedX)) > MOVEDSC || Math.abs((event.getY() - local_movedY)) > MOVEDSC) {
						MysongActivity.local_ismoved = true;
					}
					break;
				default:
					break;
				}
				return true;
			}
		});
		local_singer.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				if (local_selected_button == SINGER) {
					return false;
				}
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					local_movedX = event.getX();
					local_movedY = event.getY();
					local_singer.setBackgroundResource(R.drawable.singer_selected);
					break;
				case MotionEvent.ACTION_UP:
					if (MysongActivity.local_ismoved) {
						local_singer.setBackgroundResource(R.drawable.singer_unselected);
					} else {
						layout_local_all_playing_id.setVisibility(View.INVISIBLE);
						layout_local_folder.setVisibility(View.INVISIBLE);
						layout_local_alllist.setVisibility(View.INVISIBLE);
						layout_local_folderlist.setVisibility(View.INVISIBLE);
						local_allsong.setBackgroundResource(R.drawable.all_unselected);
						local_folder.setBackgroundResource(R.drawable.folder_unselected);
						local_selected_button = SINGER;
					}
					MysongActivity.local_ismoved = false;
					break;
				case MotionEvent.ACTION_MOVE:
					if (Math.abs((event.getX() - local_movedX)) > MOVEDSC || Math.abs((event.getY() - local_movedY)) > MOVEDSC) {
						MysongActivity.local_ismoved = true;
					}
					break;
				default:
					break;
				}
				return true;
			}
		});
		local_folder_sdcard.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!folderPath.equals(sdCardPath.getAbsolutePath())) {
					showFolder(sdCardPath.toString());
					local_list_folder.setAdapter(mFolderAdapter);
				}
			}
		});
		local_folder_pre.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!folderPath.equals(sdCardPath.getAbsolutePath())
						&& folderPath.length() >= sdCardPath.getAbsolutePath().length()) {
					showFolder(folderPath.substring(0, folderPath.lastIndexOf("/")));
					local_list_folder.setAdapter(mFolderAdapter);
				}
			}
		});
		// 最近播放
		recent_backto_localsong.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				backToMysong();
			}
		});
		recent_clear.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				RecentplayDAO recentplayDAO = new RecentplayDAO(getBaseContext());
				recentplayDAO.open();
				recentplayDAO.dropTable();
				recentplayDAO.close();
				Toast.makeText(MysongActivity.this, R.string.listemptyed, Toast.LENGTH_SHORT).show();
				// 刷新列表
				showRecentList();
			}
		});
	}

	protected void showFolder(final String path) {
		if (!SDCardOperation.IsExistSdCard()) {
			Toast.makeText(this, R.string.nosdcard, Toast.LENGTH_SHORT).show();
			return;
		}
		if (folderPath.equals(path) && mFolderAdapter != null) {
			local_list_folder.setAdapter(mFolderAdapter);
			return;
		} else if (mFolderAdapter == null) {
			mFolderAdapter = new FolderAdapter();
		}
		folderPath = path;
		mp3Filter = new FilenameFilter() {
			File tempFile;

			@Override
			public boolean accept(File dir, String filename) {
				tempFile = new File(dir.getPath() + "/" + filename);
				if (tempFile.isDirectory() && !filename.startsWith(".") && !tempFile.isHidden()
						&& tempFile.listFiles().length > 0) {
					return true;
				} else if (tempFile.isFile() && filename.endsWith(".mp3")) {
					return true;
				}
				return false;
			}
		};
		File file = new File(path);
		folderListFiles = file.listFiles(mp3Filter);
	}

	protected void recent_showRecentlist() {

	}

	protected void backToMysong() {
		layout_mySong.setVisibility(View.VISIBLE);
		layout_localSongAll.setVisibility(View.INVISIBLE);
		layout_recentplay.setVisibility(View.INVISIBLE);
		layoutIndex = MYSONG_LAYOUT;
	}

	protected void initService() {
		musicPlayerApp = (MusicPlayerApp) getApplication();
		mMusicInfoController = musicPlayerApp.getMusicInfoController();

		startService(new Intent(this, MusicPlayerService.class));
		getApplicationContext().bindService(new Intent(this, MusicPlayerService.class), mPlaybackConnection,
				Context.BIND_AUTO_CREATE);

		IntentFilter filter = new IntentFilter();
		filter.addAction(MusicPlayerService.PLAYER_PREPARE_END);
		filter.addAction(MusicPlayerService.PLAY_COMPLETED);
		filter.addAction(MusicPlayerService.PLAY_PAUSE);
		filter.addAction(MusicPlayerService.PLAY_CONTINUE);
		filter.addAction(MusicPlayerService.ERROR);
		registerReceiver(mPlayerEvtReceiver, filter);

		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case ALLSONG:
					local_list_all.setAdapter(mLocalMusicListAdapter);
					local_list_all.setDivider(null);
					setLocalsongAllListListner();
					break;

				case FOLDER:
					local_list_folder.setAdapter(mFolderAdapter);
					local_list_all.setDivider(null);
					setLocalsongFolderListListner();
					break;
				default:
					break;
				}
				removeDialog(LOADING_DIALOG);
			}
		};

		folderThread = new Thread() {
			public void run() {
				Looper.prepare();
				if (local_list_all != null) {
					showAllSongList();
					handler.sendEmptyMessage(ALLSONG);
				}
				Looper.loop();
			}
		};
	}

	protected void showAllSongList() {
		if (null == musicPlayerApp.getCursor()) {
			musicPlayerApp.initCursor();
		}
		mLocalCursor = musicPlayerApp.getCursor();
		if (null == mLocalCursor || mLocalCursor.isClosed()) {
			Toast.makeText(this, R.string.unknowerror, Toast.LENGTH_SHORT).show();
			return;
		}
		if (mLocalCursor.getCount() == 0) {
			local_all_playing_id.setText(R.string.nosong);
			return;
		}
		mLocalMusicListAdapter = new MusicListAdapter(this, R.layout.list_musicitem, mLocalCursor, new String[] {}, new int[] {},
				true);
	}

	private void setLocalsongAllListListner() {
		local_list_all.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			}
		});
		local_list_all.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View clicked, int position, long arg3) {
				if (mLocalCursor == null || mLocalCursor.getCount() == 0) {
					return;
				}
				if (!mLocalCursor.moveToPosition(position)) {
					Toast.makeText(MysongActivity.this, R.string.nosong, Toast.LENGTH_SHORT).show();
					return;
				}
				String url = ((TextView) clicked.findViewById(R.id.list_item_url)).getText().toString();
				File temp = new File(url);
				mMusicPlayerService.setAlbumID(mLocalCursor);
				TextView song_name = (TextView) clicked.findViewById(R.id.list_item_song_name);
				TextView singer = (TextView) clicked.findViewById(R.id.list_item_singer);
				TextView album = (TextView) clicked.findViewById(R.id.list_item_album);
				MusicPlayerService.setId(position);
				MusicPlayerService.setSinger(singer.getText().toString());
				MusicPlayerService.setSongname(song_name.getText().toString());
				MusicPlayerService.setAlbum(album.getText().toString());
				if (mMusicPlayerService != null && mMusicPlayerService.getMusicPath() == url && mMusicPlayerService.isPlaying()) {
					mMusicPlayerService.pause();
				} else if (mMusicPlayerService != null && temp.exists()) {
					mMusicPlayerService.stop();
					mMusicPlayerService.setMusicPath(url);
					mMusicPlayerService.start();
				} else if (!temp.exists()) {
					Toast.makeText(MysongActivity.this, R.string.notexists, Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(MysongActivity.this, R.string.unknowerror, Toast.LENGTH_SHORT).show();
				}
			}
		});

	}

	private void setLocalsongFolderListListner() {
		local_list_folder.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View clicked, int position, long arg3) {
				String url = ((TextView) clicked.findViewById(R.id.list_folderitem_url)).getText().toString();
				File file = new File(url);
				if (file.isDirectory()) {
					showFolder(url);
					local_list_folder.setAdapter(mFolderAdapter);
				} else if (file.isFile() && url.endsWith(".mp3")) {

				}
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && layoutIndex != MYSONG_LAYOUT) {
			backToMysong();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	protected void onRestart() {

		super.onRestart();
		if (null != mLocalMusicListAdapter) {
			musicPlayerApp.initCursor();
			mLocalCursor = musicPlayerApp.getCursor();
			mLocalMusicListAdapter.notifyDataSetChanged();
		}
	}

	@Override
	protected void onResume() {
		switch (layoutIndex) {
		case MYSONG_LAYOUT:

			break;
		case RECENT_LAYOUT:
			showRecentList();
			break;
		default:
			break;
		}
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// musicPlayerApp.closeCursor();
		// unbindService(mPlaybackConnection);
		stopService(new Intent(this, MusicPlayerService.class));
		// unregisterReceiver(mPlayerEvtReceiver);
		if (null != mRecentCursor) {
			mRecentCursor.close();
		}
	}

	protected void showRecentList() {
		recentplayDAO = new RecentplayDAO(this);
		recentplayDAO.open();
		mRecentCursor = recentplayDAO.getAllDataByDESC();
		if (null == mMusicPlayerService) {
			return;
		}
		mRecentMusicListAdapter = new MusicListAdapter(this, R.layout.list_musicitem, mRecentCursor, new String[] {},
				new int[] {}, false);
		recent_list.setAdapter(mRecentMusicListAdapter);
		recent_list.setDivider(null);
		if (null != recentplayDAO) {
			recentplayDAO.close();
		}
	}

	class MusicListAdapter extends SimpleCursorAdapter {
		private boolean isLoacalLayout;

		public MusicListAdapter(Context context, int layout, Cursor c, String[] from, int[] to, boolean isLoacalLayout) {
			super(context, layout, c, from, to, FLAG_REGISTER_CONTENT_OBSERVER);
			if (null == c || c.getCount() < 1) {
				Toast.makeText(MysongActivity.this, R.string.emptylist, Toast.LENGTH_SHORT).show();
				return;
			}
			this.isLoacalLayout = isLoacalLayout;
		}

		public void bindView(View view, Context context, Cursor cursor) {
			super.bindView(view, context, cursor);
			view.setBackgroundColor((cursor.getPosition() % 2 == 0) ? Color.WHITE : 0xFFF5F5F5);
			TextView num = (TextView) view.findViewById(R.id.list_item_num);
			num.setText("" + (cursor.getPosition() + 1));
			TextView song_name = (TextView) view.findViewById(R.id.list_item_song_name);
			song_name.setText(cursor.getString(cursor.getColumnIndex((isLoacalLayout == true ? MediaStore.Audio.Media.TITLE
					: KEY_SONGNAME))));
			TextView album = (TextView) view.findViewById(R.id.list_item_album);
			album.setText(cursor.getString(cursor.getColumnIndex((isLoacalLayout == true ? MediaStore.Audio.Media.ALBUM
					: KEY_ALBUM))));
			TextView singer = (TextView) view.findViewById(R.id.list_item_singer);
			singer.setText(cursor.getString(cursor.getColumnIndex((isLoacalLayout == true ? MediaStore.Audio.Media.ARTIST
					: KEY_SINGER))));
			TextView url = (TextView) view.findViewById(R.id.list_item_url);
			url.setText(cursor.getString(cursor.getColumnIndex((isLoacalLayout == true ? MediaStore.Audio.Media.DATA : KEY_URL))));
		}
	}

	class FolderAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			if (folderListFiles == null || folderListFiles.length == 0) {
				Toast.makeText(MysongActivity.this, R.string.noexistsong, Toast.LENGTH_SHORT).show();
				return 0;
			} else if (null != folderListFiles) {
				return folderListFiles.length;
			}
			return 0;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return folderListFiles[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			if (view == null) {
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = inflater.inflate(R.layout.list_folderitem, null);
			}
			File file = folderListFiles[position];
			view.setBackgroundColor(position % 2 == 0 ? Color.WHITE : 0xFFF5F5F5);
			ImageView fileicon = (ImageView) view.findViewById(R.id.list_folderitem_fileicon);
			TextView filename = (TextView) view.findViewById(R.id.list_folderitem_filename);
			TextView lastmodifydate = (TextView) view.findViewById(R.id.list_folderitem_lastmodifydate);
			lastmodifydate.setText(ConvertTime.formatDateString(MysongActivity.this, file.lastModified()));
			TextView url = (TextView) view.findViewById(R.id.list_folderitem_url);
			String pathString = file.getAbsolutePath();
			url.setText(pathString);
			if (file.isDirectory()) {
				fileicon.setImageResource(R.drawable.folder);
				File[] tempFiles = new File(pathString).listFiles();
				filename.setText(file.getName() + "( " + tempFiles.length + " )");
			} else if (file.isFile() && file.getName().endsWith(".mp3")) {
				fileicon.setImageResource(R.drawable.file_icon_mp3);
				filename.setText(file.getName());
			}

			return view;
		}

	}

	public static class MyAlertDialogFragment extends DialogFragment {

		public static MyAlertDialogFragment newInstance(int title) {
			MyAlertDialogFragment frag = new MyAlertDialogFragment();
			Bundle args = new Bundle();
			args.putInt("title", title);
			frag.setArguments(args);
			return frag;
		}

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			int title = getArguments().getInt("title");

			return new AlertDialog.Builder(getActivity()).setIcon(R.drawable.default_song_img).setTitle(title)
					.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							((MysongActivity) getActivity()).doPositiveClick();
						}
					}).create();
		}
	}

	void showDialog() {
		DialogFragment newFragment = MyAlertDialogFragment.newInstance(R.string.ok);
		newFragment.show(getFragmentManager(), "dialog");
	}

	public void doPositiveClick() {
		// Do stuff here.
		Log.i("FragmentAlertDialog", "Positive click!");
	}

	public void doNegativeClick() {
		// Do stuff here.
		Log.i("FragmentAlertDialog", "Negative click!");
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case LOADING_DIALOG:
			dialog = new ProgressDialog(this);
			dialog.setMessage("加载中...");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			return dialog;
		default:
			break;
		}
		return dialog;
	}

}
